﻿using System.Linq;
using System.Reflection;
using Autofac;
using Library.Core.Infrastructure.Common;
using Microsoft.Extensions.DependencyInjection;
using Module = Autofac.Module;

namespace Synthesize.Infrastructure.Modules
{
    public class ApplicationModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterAssemblyTypes(typeof(Library.Core.Application.ApplicationsException).Assembly)
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope();


            var appServiceAssemblies = ModuleHelper.GetAppServiceAssemblies();
            builder.RegisterAssemblyTypes(appServiceAssemblies)
               .Where(type => type.GetInterface("IEventHandler") == null)
               .AsImplementedInterfaces()
               .InstancePerLifetimeScope();
        }
    }

    public static class ModuleHelper
    {
        public static Assembly[] GetAppServiceAssemblies() => RuntimeHelper.GetAllAssemblies()
            .Where(m => m.ManifestModule.Name.StartsWith("Synthesize.") &&
                   m.ManifestModule.Name.EndsWith(".Application.dll"))
             .ToArray();
    }

    public static class ModuleExtension
    {
        public static void RegisterCapSubscribe(this IServiceCollection services)
        {
            var assemblies = ModuleHelper.GetAppServiceAssemblies();
            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetExportedTypes())
                {
                    if (type.GetInterface("IEventHandler") != null)
                    {
                        services.AddTransient(type.GetInterfaces().FirstOrDefault(), type);
                    }
                }
            }
        }
    }
}
